using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Configuration;
using ResourceBlender.DAL;
using ResourceBlender.Core;

/// <summary>
/// A page which allows changing of application settings.
/// </summary>
public partial class Settings : LocalPage
{
    /// <summary>
    /// Populates the textboxes on the page with the current settings on first load.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        pnlError.Visible = false;
    }
    /// <summary>
    /// Tests and saves the configuration.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnSave_Click(object sender, EventArgs e) {
        System.Configuration.ConnectionStringSettings conn = null;
        System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
        Database db = null;
        DatabaseType dbType = dbSelector.Mode;
        string connectionString = Database.GetConnectionString(dbType, dbSelector.Host, dbSelector.Port, dbSelector.User, dbSelector.Password, dbSelector.DatabaseName);
        try {
            db = new Database();
            db.OpenConnection(dbType, connectionString);
            KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
            appSettings["dbtype"].Value = ((int)dbSelector.Mode).ToString();
            appSettings["dbhost"].Value = dbSelector.Host;
            appSettings["dbport"].Value = dbSelector.Port.ToString();
            appSettings["dbuser"].Value = dbSelector.User;
            appSettings["dbpass"].Value = dbSelector.Password;
            appSettings["dbdatabase"].Value = dbSelector.DatabaseName;
            switch(dbSelector.Mode) {
                case DatabaseType.MySQL:
                    conn = new ConnectionStringSettings("Default", connectionString, "MySql.Data.MySqlClient");
                    break;
                case DatabaseType.SQLServer:
                    conn = new ConnectionStringSettings("Default", connectionString, "System.Data.SqlClient");
                    break;
            }
            if(config.ConnectionStrings.ConnectionStrings.IndexOf(conn) >= 0) {
                config.ConnectionStrings.ConnectionStrings.Remove("Default");
            }
            config.ConnectionStrings.ConnectionStrings.Add(conn);
            config.Save();
        } catch(System.Configuration.ConfigurationErrorsException cEx) {
            string providerName = dbType == DatabaseType.MySQL ? "MySql.Data.MySqlClient" : "System.Data.SqlClient";
            KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
            string salt = string.Empty;
            if(config.AppSettings.Settings.AllKeys.Contains("salt")) {
                salt = appSettings["salt"].Value;
            }
            Dictionary<string, string> appSettingsKeys = new Dictionary<string, string>() {
                { "dbtype", appSettings["dbtype"].Value },
                { "dbhost", appSettings["db"].Value },
                { "dbport", appSettings["dbport"].Value },
                { "dbuser", appSettings["dbuser"].Value },
                { "dbpass", appSettings["dbpass"].Value },
                { "dbdatabase", appSettings["dbdatabase"].Value },
                { "tableprefix", appSettings["tableprefix"].Value },
                { "salt", salt},
                { "webpi", "false" }
            };
            lblError.Text = I18nUtils.GetString("Errors", "ErrorNumDescription", "401a", I18nUtils.GetString("Errors", "ErrorneousConfiguration") + " - " + cEx.Message) + "<br /><br />" + ASPNETUtils.GetWebConfig(appSettingsKeys, connectionString, providerName);
            pnlError.Visible = true;
        } catch(System.UnauthorizedAccessException uEx) {
            lblError.Text = I18nUtils.GetString("Errors", "ErrorNumDescription", "402b", I18nUtils.GetString("Errors", "ASPNETAccountNoAccess") + " - " + uEx.Message);
            pnlError.Visible = true;
        } catch(InvalidOperationException iEx) {
            lblError.Text = I18nUtils.GetString("Errors", "ErrorNumDescription", "403b", iEx.Message);
            pnlError.Visible = true;
        } catch(MySql.Data.MySqlClient.MySqlException mEx) {
            lblError.Text = I18nUtils.GetString("Errors", "ErrorNumDescription", "404b", I18nUtils.GetString("Errors", "CouldNotConnectMySQL") + " - " + mEx.Message);
            pnlError.Visible = true;
        } catch(Exception ex) {
            lblError.Text = I18nUtils.GetString("Errors", "Error") + ": " + I18nUtils.GetString("Errors", "CouldNotConnectDatabase") + " - " + ex.Message;
            pnlError.Visible = true;
        }
    }
}
